package com.kaili.db.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.pojo.dto.stowage.StowageAddBean;
import com.kaili.pojo.dto.stowage.StowageDetailAddBean;
import com.kaili.pojo.dto.stowage.StowageEditBean;
import com.kaili.client.service.ILoginUserInfoService;
import com.kaili.common.OperationType;
import com.kaili.common.stock.StockInfoBean;
import com.kaili.common.stock.StockPdaInfoBean;
import com.kaili.common.util.LoginDetailUtils;
import com.kaili.db.mapper.HsEwbsStowageMapper;
import com.kaili.db.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.kaili.pojo.entity.*;
import com.kaili.pojo.vo.EwbQueryVO;
import com.kaili.pojo.vo.StowageDetailPdaVO;
import com.kaili.pojo.vo.StowageDetailPdaVO;
import com.kaili.pojo.vo.StowageInfoVO;
import com.kaili.pojo.vo.StowageQueryVO;
import com.kaili.common.exception.BaseExcept;
import com.kaili.utils.DateUtils;
import com.kaili.common.util.SnowflakeIdFactory;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

import static com.kaili.except.ResponseStatus.DATA_NOT_EXIST;
import static com.kaili.except.ResponseStatus.STOWAGE_ADD_DUPLICATE;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cgm
 * @since 2018-05-08
 */
@Service
@Transactional
public class HsEwbsStowageServiceImpl extends ServiceImpl<HsEwbsStowageMapper, HsEwbsStowage> implements IHsEwbsStowageService {


    @Autowired
    ILoginUserInfoService loginUserInfoService;

    @Autowired
    IHsEwbsStowageDetailService  ewbsStowageDetailService;

    @Autowired
    IHsOptQueryService queryService;

    @Autowired
    IHsOptEwbService optEwbService;

    @Autowired
    IHsEwbSubStockService subStockService;

    @Autowired
    IHsEwbsStowageSubService ewbsStowageSubService;

    @Override
    @Transactional
    public int doAddStowage(StowageAddBean addBean) {
        boolean isAdd = true;//是新增 or 修改
        Integer userId = LoginDetailUtils.getCurrentEmployeeId();
        Integer siteId = LoginDetailUtils.getSiteId();
        String operationId = addBean.getOperationId();
        String ewbNo = null;

        if(operationId != null){
            isAdd = false;
        }

        HsEwbsStowage ewbsStowage = new HsEwbsStowage();
        BeanUtils.copyProperties(addBean,ewbsStowage);
        if(isAdd){
            // 1.插入配载单
            operationId = String.valueOf(SnowflakeIdFactory.getNextId());
            addBean.setOperationId(operationId);
            ewbsStowage.setOperationId(operationId);
            ewbsStowage.setCreatedTime(DateUtils.getCurrentDate());
            ewbsStowage.setCreatedBy(userId);
            ewbsStowage.setSiteId(siteId);
            ewbsStowage.setStatus(0);
            baseMapper.insert(ewbsStowage);
        }else{
            // 2.修改配载单
            ewbsStowage.setModifiedTime(DateUtils.getCurrentDate());
            ewbsStowage.setModifiedBy(userId);
            baseMapper.updateById(ewbsStowage);

            delete(operationId);
        }

        List<StowageDetailAddBean> list =  addBean.getEwbsStowageDetailList();
        List<HsEwbsStowageDetail> stowageDetailList = new ArrayList<HsEwbsStowageDetail>();
        List<HsOptQuery> queryList = new ArrayList<HsOptQuery>();
        for (StowageDetailAddBean stowageDetailAddBean:list) {
            ewbNo = stowageDetailAddBean.getEwbNo();
            //存储配载详情数据
            HsEwbsStowageDetail ewbsStowageDetail = new HsEwbsStowageDetail();
            BeanUtils.copyProperties(stowageDetailAddBean,ewbsStowageDetail);
            if(null!=addBean.getNextSiteId()){
                ewbsStowageDetail.setNextSiteId(addBean.getNextSiteId());
            }
            ewbsStowageDetail.setOutPiece(stowageDetailAddBean.getStowagePiece());
            ewbsStowageDetail.setOutWeight(stowageDetailAddBean.getStowageWeight());
            ewbsStowageDetail.setOutVol(stowageDetailAddBean.getStowageVol());
            ewbsStowageDetail.setDeviceCode(addBean.getDeviceCode());
            ewbsStowageDetail.setScanSourceId(addBean.getScanSourceId());
            ewbsStowageDetail.setSiteId(addBean.getSiteId());
            ewbsStowageDetail.setStowageType(addBean.getStowageType());
            ewbsStowageDetail.setOperationId(operationId);
            ewbsStowageDetail.setRdStatus(1);
            stowageDetailList.add(ewbsStowageDetail);

            //存储快件跟踪记录
            HsOptQuery optQuery = new HsOptQuery();
            optQuery.setEwbNo(ewbsStowageDetail.getEwbNo());
            optQuery.setStep(OperationType.LOADING);//1开单  2配载  3发车  4在途  5到车  6派件  7签收
            optQuery.setOperationId(operationId);
            optQuery.setOperationTime(DateUtils.getCurrentDate());
            optQuery.setOperator(userId);
            optQuery.setOperationSiteId(siteId);
            queryList.add(optQuery);

            //更新子单库存
            List<HsEwbSubStock> ewbSubStockList = new ArrayList<>();
            Integer scanSourceId = addBean.getScanSourceId();
            if(scanSourceId!=null&&scanSourceId==2){  //1:web   2:pda
                StockPdaInfoBean  stockPdaInfoBean = new StockPdaInfoBean();
                stockPdaInfoBean.setEwbNo(ewbsStowageDetail.getEwbNo());
                stockPdaInfoBean.setSize(stowageDetailAddBean.getSubEwbs().size());
                stockPdaInfoBean.setSiteId(siteId);
                stockPdaInfoBean.setSubEwbs(stowageDetailAddBean.getSubEwbs());
                ewbSubStockList = subStockService.stowageEwbByPda(stockPdaInfoBean);
            }else{
                StockInfoBean stockInfoBean = new StockInfoBean();
                stockInfoBean.setEwbNo(ewbsStowageDetail.getEwbNo());
                stockInfoBean.setSize(stowageDetailAddBean.getStowagePiece());
                stockInfoBean.setSiteId(siteId);
                ewbSubStockList = subStockService.stowageEwbByBs(stockInfoBean);
            }

            //插入配载单和子单关联
            List<HsEwbsStowageSub> ewbsStowageSubList = new ArrayList<>();
            try{
                if(CollectionUtils.isNotEmpty(ewbSubStockList)){
                    for (HsEwbSubStock ewbSubStock:ewbSubStockList ) {
                        HsEwbsStowageSub ewbsStowageSub = new HsEwbsStowageSub();
                        ewbsStowageSub.setEwbNo(ewbsStowageDetail.getEwbNo());
                        ewbsStowageSub.setOperationId(operationId);
                        ewbsStowageSub.setCreatedTime(DateUtils.getCurrentDate());
                        ewbsStowageSub.setSiteId(siteId);
                        ewbsStowageSub.setSubEwb(ewbSubStock.getSubEwb());
                        ewbsStowageSubList.add(ewbsStowageSub);
                    }
                    ewbsStowageSubService.insertBatch(ewbsStowageSubList);
                }
            }catch (Exception e){
                String exception = e.getCause().getMessage();
                if(exception.toLowerCase().contains("duplicate entry")){
                    throw new BaseExcept(STOWAGE_ADD_DUPLICATE);
                }
            }

            //修改运单状态为已配载 或者 未配载
            Wrapper<HsEwbSubStock> where2 = new EntityWrapper<>();
            where2.where("ewb_no={0} and site_id={1} and status={2}", stowageDetailAddBean.getEwbNo(), siteId, OperationType.STOCK_ON);
            List<HsEwbSubStock> stocks = subStockService.selectList(where2);
            if(CollectionUtils.isEmpty(stocks)){
                //查询本站库存,为0说明已全部配载,则更新运单配载状态为已配载
                Wrapper<HsOptEwb> wrapper = new EntityWrapper<>();
                wrapper.where("ewb_no={0} and is_loading={1}", ewbNo,0);
                HsOptEwb ewb1 = new HsOptEwb();
                ewb1.setIsLoading(1);
                ewb1.setLoadingTime(DateUtils.getCurrentDate());
                optEwbService.update(ewb1, wrapper);
            }
        }

        //添加配载详情数据
        ewbsStowageDetailService.insertBatch(stowageDetailList);
        //插入快件跟踪记录
        if(CollectionUtils.isNotEmpty(queryList)){
            queryService.insertBatch(queryList);
        }

        //配载发车调用财务存储过程p_fin_ewbs_stowage_input
        JSONArray array = new JSONArray();
        JSONObject obj = new JSONObject();
        obj.put("operation_id",operationId);
        obj.put("user_id",ewbsStowage.getDriverId());//司机ID
        obj.put("site_id",ewbsStowage.getSiteId());//配载单制作网点id
        obj.put("amount",ewbsStowage.getCarryFreightCharge());//承运费
        obj.put("ewb_no","");//运单号
        obj.put("remark",ewbsStowage.getOutRemark());//备注
        if(isAdd){
            obj.put("created_by",ewbsStowage.getCreatedBy());//创建人
            obj.put("created_time",DateUtils.dateToStrLong(ewbsStowage.getCreatedTime()));//创建时间
            obj.put("operate_type",1);//操作类型，1表示新增 2表示修改 3表示删除
        }else{
            obj.put("created_by",ewbsStowage.getModifiedBy());//创建人
            obj.put("created_time",DateUtils.dateToStrLong(ewbsStowage.getModifiedTime()));//创建时间
            obj.put("operate_type",2);//操作类型，1表示新增 2表示修改 3表示删除
        }
        array.add(obj);
        Map<String,Object> map = new HashMap<>();
        map.put("v_param",array.toJSONString());
        baseMapper.callEwbsStowageInputFinProduce(map);

        return 0;
    }

    @Override
    public Page<StowageQueryVO> queryStowagePageList(Page<StowageQueryVO> pager, Map search) {
        return pager.setRecords(baseMapper.queryStowageList(pager,search));
    }

    @Override
    public List<StowageQueryVO> queryStowageList(Map search) throws BaseExcept {
        return baseMapper.queryStowageList(search);
    }

    @Override
    @Transactional
    public int doConfirmSend(List<String> list) {
        Integer loginUserId = loginUserInfoService.getLoginUserId();
        Integer loginSiteId = loginUserInfoService.getLoginSiteId();
        for (String operationId: list) {
            HsEwbsStowage ewbsStowage = new HsEwbsStowage();
            ewbsStowage.setOperationId(operationId);
            ewbsStowage.setCarSendTime(DateUtils.getCurrentDate());
            ewbsStowage.setOutConfirmBy(loginUserId);
            ewbsStowage.setStatus(1);
            if(baseMapper.updateById(ewbsStowage)<=0){
                throw new BaseExcept(DATA_NOT_EXIST);
            }

            Wrapper<HsEwbsStowageDetail> wrapper_detail = new EntityWrapper<>();
            wrapper_detail.where("operation_id={0}", operationId);
            List<HsEwbsStowageDetail> stowageDetailList  = ewbsStowageDetailService.selectList(wrapper_detail);
            for (HsEwbsStowageDetail detail: stowageDetailList) {
                String  ewbNo = detail.getEwbNo();
                //确认发车时 快件跟踪添加发车和在途2条记录
                HsOptQuery optQuery = new HsOptQuery();
                optQuery.setEwbNo(ewbNo);
                optQuery.setStep(OperationType.SENDING);//1开单  2配载  3发车  4在途  5到车  6派件  7签收
                optQuery.setOperationId(operationId);
                optQuery.setOperationTime(DateUtils.getCurrentDate());
                optQuery.setOperator(loginUserId);
                optQuery.setOperationSiteId(loginSiteId);
                queryService.insert(optQuery);

                HsOptQuery optQueryNew = new HsOptQuery();
                optQueryNew.setEwbNo(ewbNo);
                optQueryNew.setStep(OperationType.ONTHEWAY);//1开单  2配载  3发车  4在途  5到车  6派件  7签收
                optQueryNew.setOperationId(operationId);
                optQueryNew.setOperationTime(DateUtils.getCurrentDate());
                optQueryNew.setOperator(optEwbService.selectDriver(operationId));
                optQueryNew.setOperationSiteId(loginSiteId);
                queryService.insert(optQueryNew);

                HsEwbsStowage queryEwbsStowage = baseMapper.selectById(operationId);
                if(null != queryEwbsStowage){
                    StockPdaInfoBean stockPdaInfoBean = new StockPdaInfoBean();
                    if(null!=queryEwbsStowage.getNextSiteId()){
                        stockPdaInfoBean.setNextSiteId(queryEwbsStowage.getNextSiteId());
                    }else{
                        stockPdaInfoBean.setNextSiteId(queryEwbsStowage.getDestinationSiteId());
                    }

                    //查询配载单关联的子单号集合
                    Wrapper<HsEwbsStowageSub> wrapper = new EntityWrapper<>();
                    wrapper.where("operation_id={0} and ewb_no={1}", operationId,ewbNo);
                    List<HsEwbsStowageSub>  ewbsStowageSubs= ewbsStowageSubService.selectList(wrapper);
                    List<String> subEwbs = new ArrayList<>();
                    for (HsEwbsStowageSub ewbsStowageSub : ewbsStowageSubs) {
                        subEwbs.add(ewbsStowageSub.getSubEwb());
                    }
                    stockPdaInfoBean.setSiteId(loginSiteId);
                    stockPdaInfoBean.setSubEwbs(subEwbs);
                    stockPdaInfoBean.setEwbNo(ewbNo);
                    stockPdaInfoBean.setSize(subEwbs.size());

                    if(CollectionUtils.isNotEmpty(subEwbs)){
                        subStockService.sendEwbByPda(stockPdaInfoBean);
                    }
                }

            }

        }
        return 0;
    }

    @Override
    public List<EwbQueryVO> queryEwbListByStowageNo(Map searchMap) {
        return optEwbService.queryEwbListByStowageNo(searchMap);
    }

    @Override
    public StowageInfoVO queryStowageInfo(Map<String, Object> searchMap) {
        return baseMapper.queryStowageInfo(searchMap);
    }

    @Override
    @Transactional
    public int updateStowage(StowageEditBean editBean) {
       // Integer loginUserId = loginUserInfoService.getLoginUserId();
        Integer modifyUserId = editBean.getModifyUserId();
        Integer loginSiteId = loginUserInfoService.getLoginSiteId();

        Map search = new HashMap();
        search.put("operation_id", editBean.getOperationId());
        search.put("rd_status", 1);
        List<HsEwbsStowageDetail> detailsOld = ewbsStowageDetailService.selectByMap(search);
        List<HsEwbsStowageDetail> orgs = new ArrayList<>();
        List<HsEwbsStowageDetail> deletes = new ArrayList<>();
        // 获取新增及原始数据
        for (int j = 0; j < editBean.getEwbsStowageDetailList().size(); j++) {
            EwbQueryVO  ewbQueryVO = editBean.getEwbsStowageDetailList().get(j);
            HsEwbsStowageDetail detailNew = new HsEwbsStowageDetail();//新添加明细

            detailNew.setOperationId(editBean.getOperationId());
            detailNew.setOutPiece(ewbQueryVO.getStowagePiece());
            detailNew.setOutWeight(BigDecimal.valueOf(ewbQueryVO.getStowageWeight()));
            detailNew.setOutVol(BigDecimal.valueOf(ewbQueryVO.getStowageVol()));
            detailNew.setEwbNo(ewbQueryVO.getEwbNo());
            detailNew.setNextSiteId(editBean.getNextSiteId());
            detailNew.setOutScanPiece(ewbQueryVO.getStowagePiece());
            detailNew.setScanSourceId(1);
            detailNew.setRdStatus(1);
            detailNew.setSiteId(loginSiteId);

            HsEwbsStowageDetail detailOld = null;
            boolean has = false;
            for (int i = 0; i < detailsOld.size(); i++) {
                detailOld = detailsOld.get(i);//已配载明细数据旧
                if (detailNew.getEwbNo().equals(detailOld.getEwbNo())) {
                    has = true;
                    break;
                }
            }
            if (!has) {
                ewbsStowageDetailService.insert(detailNew);
                //updates.add(n);
                //新增快件跟踪记录
                HsOptQuery optQuery = new HsOptQuery();
                optQuery.setEwbNo(detailNew.getEwbNo());
                optQuery.setStep(OperationType.LOADING);//1开单  2配载  3发车  4在途  5到车  6派件  7签收
                optQuery.setOperationId(editBean.getOperationId());
                optQuery.setOperationTime(DateUtils.getCurrentDate());
                optQuery.setOperator(modifyUserId);
                optQuery.setOperationSiteId(loginSiteId);
                queryService.insert(optQuery);

            } else {

                    int newPiece = detailNew.getOutPiece().intValue();
                    int oldPiece = detailOld.getOutPiece().intValue();
                    //运单号存在但是配载件数不一致,如果件数改大则修改子单库存状态数据为已配载,并插入配载单子单关联表
                    if(newPiece>oldPiece){
                        //修改子单库存状态数据为已配载
                        int diff = newPiece - oldPiece;
                        StockInfoBean stockInfoBean = new StockInfoBean();
                        stockInfoBean.setEwbNo(detailNew.getEwbNo());
                        stockInfoBean.setSize(diff);
                        stockInfoBean.setSiteId(loginSiteId);
                        List<HsEwbSubStock> ewbSubStockList = subStockService.stowageEwbByBs(stockInfoBean);
                        //插入配载单子单关联表
                        List<HsEwbsStowageSub> ewbsStowageSubList = new ArrayList<>();
                        try{
                            if(CollectionUtils.isNotEmpty(ewbSubStockList)){
                                for (HsEwbSubStock ewbSubStock:ewbSubStockList ) {
                                    HsEwbsStowageSub ewbsStowageSub = new HsEwbsStowageSub();
                                    ewbsStowageSub.setEwbNo(detailNew.getEwbNo());
                                    ewbsStowageSub.setOperationId(editBean.getOperationId());
                                    ewbsStowageSub.setCreatedTime(DateUtils.getCurrentDate());
                                    ewbsStowageSub.setSiteId(loginSiteId);
                                    ewbsStowageSub.setSubEwb(ewbSubStock.getSubEwb());
                                    ewbsStowageSubList.add(ewbsStowageSub);
                                }
                                ewbsStowageSubService.insertBatch(ewbsStowageSubList);
                            }
                        }catch (Exception e){
                            String exception = e.getCause().getMessage();
                            if(exception.toLowerCase().contains("duplicate entry")){
                                throw new BaseExcept(STOWAGE_ADD_DUPLICATE);
                            }
                        }

                    }else if(newPiece<oldPiece){ //如果件数改小则修改子单库存状态数据为已在库,并删除配载单子单关联表数据

                        //首先要查询该配载单关联的子单号
                        Wrapper<HsEwbsStowageSub> stowageSubWrapper = new EntityWrapper<>();
                        stowageSubWrapper.where("operation_id ={0} and ewb_no ={1}",editBean.getOperationId(),detailNew.getEwbNo());
                        List<String> list = new ArrayList();
                        list.add("sub_ewb");
                        stowageSubWrapper.orderDesc(list);
                        List<HsEwbsStowageSub>  stowageSubList = ewbsStowageSubService.selectList(stowageSubWrapper);
                        List<HsEwbSubStock> subs = new ArrayList<>();
                        Integer siteId = 0;
                        int diff = oldPiece - newPiece;
                        for (int i=0;i<diff;i++){
                            HsEwbSubStock  ewbSubStock= new HsEwbSubStock();
                            ewbSubStock.setSubEwb(stowageSubList.get(i).getSubEwb());
                            subs.add(ewbSubStock);
                            siteId =stowageSubList.get(i).getSiteId();
                        }

                        //修改该网点该配载单之前配载的子单库存状态为在库
                        Map updateInfo = new HashMap();
                        updateInfo.put("siteId",siteId);
                        updateInfo.put("subs",subs);
                        updateInfo.put("status",OperationType.STOCK_ON);
                        subStockService.updateBatch(updateInfo);

                        for (HsEwbSubStock ewbSubStock: subs) {
                            //删除配载单子单关联数据
                            Wrapper<HsEwbsStowageSub> stowageSubWrapperDel = new EntityWrapper<>();
                            stowageSubWrapperDel.where("operation_id ={0} and sub_ewb ={1}",editBean.getOperationId(),ewbSubStock.getSubEwb());
                            ewbsStowageSubService.delete(stowageSubWrapperDel);
                        }
                    }
                //修改配载单明细表件数体积重量
                if(newPiece != oldPiece){
                    ewbsStowageDetailService.updateByOperationIdAndEwbNo(detailNew);
                }
                orgs.add(detailOld);//编辑前和编辑后都存在的
            }
        }
        if(CollectionUtils.isNotEmpty(orgs)){
            // 获取删除数据
            for (int i = 0; i < detailsOld.size(); i++) {
                HsEwbsStowageDetail detail = detailsOld.get(i);
                HsEwbsStowageDetail org = null;
                boolean has = false;
                for (int j = 0; j < orgs.size(); j++) {
                    //org = deletes.get(j);
                    if (orgs.get(j).getEwbNo().equals(detail.getEwbNo())) {
                        has = true;
                        break;
                    }
                }
                if (!has) {

                    Wrapper<HsEwbsStowageDetail> ewbsStowageDetailWrapper = new EntityWrapper<>();
                    ewbsStowageDetailWrapper.where("operation_id={0} ", detail.getOperationId());
                    //删除配载单明细数据
                    ewbsStowageDetailService.delete(ewbsStowageDetailWrapper);



                    //首先要查询该配载单关联的子单号
                    Wrapper<HsEwbsStowageSub> stowageSubWrapper = new EntityWrapper<>();
                    stowageSubWrapper.where("operation_id ={0} and ewb_no ={1}",detail.getOperationId(),detail.getEwbNo());
                    List<HsEwbsStowageSub>  stowageSubList = ewbsStowageSubService.selectList(stowageSubWrapper);
                    List<HsEwbSubStock> subs = new ArrayList<>();
                    Integer siteId = 0;
                    for (HsEwbsStowageSub ewbsStowageSub: stowageSubList) {
                        HsEwbSubStock  ewbSubStock= new HsEwbSubStock();
                        ewbSubStock.setSubEwb(ewbsStowageSub.getSubEwb());
                        subs.add(ewbSubStock);
                        siteId = ewbsStowageSub.getSiteId();
                    }
                    if(CollectionUtils.isNotEmpty(subs)){
                        //修改该网点该配载单之前配载的子单库存状态为在库
                        Map updateInfo = new HashMap();
                        updateInfo.put("siteId",siteId);
                        updateInfo.put("subs",subs);
                        updateInfo.put("status",OperationType.STOCK_ON);
                        subStockService.updateBatch(updateInfo);
                    }


                    //deletes.add(n);
                    //删除配载单子单关联数据
                    ewbsStowageSubService.delete(stowageSubWrapper);

                    //删除快件跟踪记录
                    Wrapper<HsOptQuery> wrapper = new EntityWrapper<>();
                    wrapper.where("ewb_no={0} and step={1} and operation_id ={2}",
                            detail.getEwbNo(), OperationType.LOADING,editBean.getOperationId());
                    queryService.delete(wrapper);
                }
            }
        }else{//不存在编辑前和编辑后都在的,说明编辑之前选择的托运单都已删除
            for (int i = 0; i < detailsOld.size(); i++) {
                HsEwbsStowageDetail detail = detailsOld.get(i);

                //删除配载单明细数据
                ewbsStowageDetailService.deleteById(detail);

                //首先要查询该配载单关联的子单号
                Wrapper<HsEwbsStowageSub> stowageSubWrapper = new EntityWrapper<>();
                stowageSubWrapper.where("operation_id ={0} and ewb_no ={1}",detail.getOperationId(),detail.getEwbNo());
                List<HsEwbsStowageSub>  stowageSubList = ewbsStowageSubService.selectList(stowageSubWrapper);
                List<HsEwbSubStock> subs = new ArrayList<>();
                Integer siteId = 0;
                for (HsEwbsStowageSub ewbsStowageSub: stowageSubList) {
                    siteId = ewbsStowageSub.getSiteId();
                    HsEwbSubStock  ewbSubStock= new HsEwbSubStock();
                    ewbSubStock.setSubEwb(ewbsStowageSub.getSubEwb());
                    subs.add(ewbSubStock);
                }
                //修改该网点该配载单之前配载的子单库存状态为在库
                Map updateInfo = new HashMap();
                updateInfo.put("siteId",siteId);
                updateInfo.put("subs",subs);
                updateInfo.put("status",OperationType.STOCK_ON);
                subStockService.updateBatch(updateInfo);

                //deletes.add(n);
                //删除配载单子单关联数据
                ewbsStowageSubService.delete(stowageSubWrapper);

                //删除快件跟踪记录
                Wrapper<HsOptQuery> wrapper = new EntityWrapper<>();
                wrapper.where("ewb_no={0} and step={1} and operation_id ={2}",
                        detail.getEwbNo(), OperationType.LOADING,editBean.getOperationId());
                queryService.delete(wrapper);
            }

        }
        HsEwbsStowage ewbsStowage = new HsEwbsStowage();
        BeanUtils.copyProperties(editBean,ewbsStowage);
        ewbsStowage.setSiteId(loginSiteId);
        ewbsStowage.setModifiedTime(DateUtils.getCurrentDate());
        ewbsStowage.setModifiedBy(loginUserInfoService.getLoginUserId());
        baseMapper.updateById(ewbsStowage);

        //配载调用财务存储过程p_fin_ewbs_stowage_input
        JSONArray array = new JSONArray();
        JSONObject obj = new JSONObject();
        obj.put("operation_id",ewbsStowage.getOperationId());
        obj.put("user_id",ewbsStowage.getDriverId());//司机ID
        obj.put("site_id",ewbsStowage.getSiteId());//配载单制作网点id
        obj.put("amount",ewbsStowage.getCarryFreightCharge());//承运费
        obj.put("ewb_no","");//运单号
        obj.put("created_by",ewbsStowage.getModifiedBy());//创建人
        obj.put("created_time",DateUtils.dateToStrLong(ewbsStowage.getModifiedTime()));//创建时间
        obj.put("remark",ewbsStowage.getOutRemark());//备注
        obj.put("operate_type",2);//操作类型，1表示新增 2表示修改 3表示删除
        array.add(obj);
        Map<String,Object> map = new HashMap<>();
        map.put("v_param",array.toJSONString());
        baseMapper.callEwbsStowageInputFinProduce(map);

        return 0;
    }

    @Override
    @Transactional
    public int deleteStowage(String operationId) {
        HsEwbsStowage ewbsStowage = new HsEwbsStowage();
        ewbsStowage.setOperationId(operationId);
        ewbsStowage.setRdStatus(0);
        baseMapper.updateById(ewbsStowage);

        delete(operationId);

        //删除配载调用财务存储过程p_fin_ewbs_stowage_input
        JSONArray array = new JSONArray();
        JSONObject obj = new JSONObject();
        obj.put("operation_id",ewbsStowage.getOperationId());
        obj.put("user_id",ewbsStowage.getDriverId());//司机ID
        obj.put("site_id",ewbsStowage.getSiteId());//配载单制作网点id
        obj.put("amount",ewbsStowage.getCarryFreightCharge());//承运费
        obj.put("ewb_no","");//运单号
        obj.put("created_by",ewbsStowage.getModifiedBy());//创建人
        obj.put("created_time",DateUtils.dateToStrLong(new Date()));//删除时间
        obj.put("remark",ewbsStowage.getOutRemark());//备注
        obj.put("operate_type",3);//操作类型，1表示新增 2表示修改 3表示删除
        array.add(obj);
        Map<String,Object> map = new HashMap<>();
        map.put("v_param",array.toJSONString());
        baseMapper.callEwbsStowageInputFinProduce(map);

        return 0;
    }

    private void delete(String operationId){
        //删除配载详情数据
        Wrapper<HsEwbsStowageDetail> stowageDetailWrapper = new EntityWrapper<>();
        stowageDetailWrapper.where("operation_id ={0}", operationId);
        ewbsStowageDetailService.delete(stowageDetailWrapper);

        //删除快件跟踪记录
        Wrapper<HsOptQuery> optQueryWrapper = new EntityWrapper<>();
        optQueryWrapper.where("operation_id ={0}", operationId);
        queryService.delete(optQueryWrapper);

        //还原子单库存为在库
        Wrapper<HsEwbsStowageSub> stowageSubWrapper = new EntityWrapper<>();
        stowageSubWrapper.where("operation_id ={0}",operationId);
        List<HsEwbsStowageSub>  subs = ewbsStowageSubService.selectList(stowageSubWrapper);
        if(CollectionUtils.isNotEmpty(subs)){
            Map updateInfo = new HashMap();
            updateInfo.put("siteId",subs.get(0).getSiteId());
            updateInfo.put("subs",subs);
            updateInfo.put("status",OperationType.STOCK_ON);
            subStockService.updateBatch(updateInfo);
        }

        //还原运单状态为未配载
        Map updateInfo = new HashMap();
        updateInfo.put("isLoading",0);
        updateInfo.put("subs",subs);
        optEwbService.updateBatch(updateInfo);

        //删除配载单和子单关联
        ewbsStowageSubService.delete(stowageSubWrapper);
    }


    private int modifyStowageInfo(StowageEditBean bean) {
        HsEwbsStowage ewbsStowage = new HsEwbsStowage();
        ewbsStowage.setOperationId(bean.getOperationId());
        ewbsStowage.setModifiedTime(DateUtils.getCurrentDate());
        ewbsStowage.setModifiedBy(loginUserInfoService.getLoginUserId());
        return baseMapper.updateById(ewbsStowage);
    }

    @Override
    public boolean isStowage(String ewbNo){
        Map<String, Object> search = new HashMap<String, Object>();
        search.put("ewb_no",ewbNo);
        List<HsEwbsStowageDetail> list = ewbsStowageDetailService.selectByMap(search);
        if(list != null & list.size()>0){
            return true;
        }

        return false;
    }
//    queryStowageSubEwbByPda
    @Override
    public List<StowageDetailPdaVO> queryStowageDetailByPda(Map search) {
        return baseMapper.queryStowageDetailByPda(search);
    }

    @Override
    public List<String> queryStowageSubEwbByPda(Map search) {
        return baseMapper.queryStowageSubEwbByPda(search);
    }

}
